// 页面基类
module.exports = Behavior({
  properties: {},
  data: {
    href: 'https://wadmin.xuming365.com',
    host: 'https://wadmin.xuming365.com/api',

    imgHost: 'https://wadmin.xuming365.com/api/v1/resources',
    cover: "?x-oss-process=video/snapshot,t_1",
    userInfo: { //用户数据
    },
    /**顶部导航栏背景透明度 */
    bgA: 0,
  },
  created: function () {},
  attached: function () {},
  ready: function () {
    this.data.userInfo = getApp().globalData.userInfo;

    // this.check_mobile();
  },

  methods: {
    onPageScroll: function (ev) {
      // console.log('onPageScroll', ev);
      this.setData({
        bgA: ev.scrollTop / 200
      })
    },
    onLoad: function (options) {
      // console.log('基类 onload');
      this.data.userInfo = getApp().globalData.userInfo;
    },
    /**
     * 更新用户数据
     */
    req_userInfo() {
      this.request({
        url: this.data.host + '/api/member/getMemberInfo',
        method: "POST"
      }, res => {
        // console.log(res);
        getApp().globalData.userInfo = res.data;
        this.setData({
          userInfo: res.data
        })
      })
    },
    /**登陆状态更新之后重载的方法 */
    login_reload() {
      // console.log("执行基类重载方法")
      // this.data.userInfo = getApp().globalData.userInfo;
    },
    /**拨打客服电话 */
    call_phone(e) {
      // e.currentTarget
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.tel
      })
    },
    /**隐藏弹窗通用方法 */
    hide_popup(e) {
      let obj = {};
      obj[e.currentTarget.dataset.field] = false;
      this.setData(obj)
    },
    /**显示弹窗通用方法 */
    show_popup(e) {
      let obj = {};
      obj[e.currentTarget.dataset.field] = true;
      this.setData(obj)
    },

    get_imgUrl(url, w = 200) {
      let thumb = '/assets/common/logo.png';
      if (url) {
        // return `${AppUtil.imgHost}${url}?x-oss-process=image/resize,w_${w}`;
        thumb = this.data.imgHost + url + '?x-oss-process=image/resize,w_' + w;
      }
      return thumb
    },

    s_to_hs(s) {
      //计算分钟
      //算法：将秒数除以60，然后下舍入，既得到分钟数
      var h;
      h = Math.floor(s / 60);
      //计算秒
      //算法：取得秒%60的余数，既得到秒数
      s = s % 60;
      //将变量转换为字符串
      h += '';
      s += '';
      //如果只有一位数，前面增加一个0
      h = (h.length == 1) ? '0' + h : h;
      s = (s.length == 1) ? '0' + s : s;
      return h + ':' + s;
    },




    /**
     * 网络请求封装
     * @param {*} req_data  
     * url 请求地址,
     * loadingTip:加载中提示，如果存在，先显示loading
     * @param {*} success_func 成功回调方法
     * @param {*} fail_func 失败回调方法,code 不为零时也会调用
     * @param {*} complete 最终执行的方法
     */
    request: function (req_data, success_func, fail_func = null, complete = null) {
      let that = this;
      let Authorization = wx.getStorageSync('Authorization');

      if (req_data.loadingTip) {
        wx.showLoading({
          title: req_data.loadingTip,
          mask: true
        })
      }
      if (!req_data.header) {
        req_data.header = {
          'content-type': 'application/json',

          'Accept': 'application/json, text/javascript, */*; q=0.01'
        };
      }
      if (Authorization) {
        req_data.header.Authorization = Authorization;
      }
      req_data.success = function (res) { //成功处理
        if (res.statusCode == 200) {
          if (res.header.Authorization) {
            wx.setStorage({
              data: 'Bearer ' + res.header.Authorization,
              key: 'Authorization',
            })
          }
          if (res.data && res.data.data && res.data.data.session_key) {
            wx.setStorageSync('session_key', res.data.data.session_key)
          }
          let data = res.data;
          if (data.code == 200) {
            // setTimeout(() => {
            //   success_func(data.result || data);
            // }, 100);
            success_func(data.result || data);
          } else if (data.code == 401 || data.code == 403) {
            wx.navigateTo({
              url: '/pages/login/index',

            })
          } else if (data.code == 408) {
            wx.showModal({

              showCancel: true,
              title: '提示',
              content: "请先实名",
              success: (result) => {
                if (result.confirm) {
                  wx.redirectTo({
                    url: '/pages/usercenter/identity',
                  })
                } else {
                  wx.navigateBack({
                    delta: 1,

                  })
                }
              },
              fail: (res) => {},
              complete: (res) => {},
            })

          } else if (data.code == 407) {
            wx.showToast({
              title: '没有权限',
              mask: true,
              icon: 'error'

            })
          } else {
            if (fail_func) {
              return fail_func(data);
            }
            wx.showModal({
              showCancel: false,
              content: data.result || data.msg + "" || data.message + "" || JSON.stringify(data),
            })

          }
        } else if (res.statusCode == 401) {
          that.login();
        } else {
          console.log("res.statusCode", res);
          if (fail_func) {
            return fail_func(res);
          }
          wx.showModal({
            showCancel: false,
            content: "网络异常(" + res.statusCode + ")",
          })

        }
      };
      req_data.fail = function (e) { //失败处理
        fail_func ? fail_func(e) : wx.showModal({
          showCancel: false,
          content: '网络异常：' + e.errMsg
        });
      }
      req_data.complete = function (e) { //失败处理
        req_data.loadingTip ? wx.hideLoading() : '';
        complete ? complete(e) : '';
      }
      wx.request(req_data);
    },

    /**登陆方法 */
    login() {
      this.setData({
        isLoading: true
      })
      let that = this;
      wx.login({
        success(res) {
          if (res.code) {
            //发起网络请求
            that.request({
              url: that.data.host + '/apiToker/member/base/openIdAndSessionKey',
              data: {
                code: res.code
              },
              method: "POST"
            }, res => {
              that.data.openid = res.data.openid;
              that.data.unionId = res.data.unionid;
              getApp().globalData.loginBack = true;
              that.onShow();
            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        },
      });
      // this.request({
      //   url: this.data.host + '/apiToker/member/base/testToken',
      //   method: "POST",
      //   data: {
      //     memberId: 10056
      //   },
      // }, res => {
      //   let state = false;
      //   let token = wx.getStorageSync('Authorization');
      //   if (token.length == 0 || token == undefined || token == null) {
      //     state = true;
      //   }
      //   wx.setStorageSync("Authorization", "Bearer " + res.data);
      //   if (state) {
      //     wx.redirectTo({
      //       url: '/pages/homePage/home/home',
      //     })
      //   } else {
      //     wx.navigateBack({
      //       delta: 1,
      //     })
      //   }
      //   this.setData({
      //     isLoading: false,
      //   })
      //   app.globalData.loginBack = true;
      // })
    }
  }
})